<?php

class Util {

	private static $isDebugging = true;
	private static $usingAlert = false;

	public function __construct() {
		echo "Construindo Util";
	}

	public static function debug($message) {
		if( self::$isDebugging ) {
			if( self::$usingAlert ) {
				self::alert("Debug Message on " . date("l dS \of F Y h:i:s A") . "\\n-----------------------------------------------\\n$message");
			} else {
				echo "Debug Message on " . date("l dS \of F Y h:i:s A") . " : $message <br />";
			}
		}
	}
	
	public static function alert($message) {
		echo "<script>alert(\"$message\");</script>";
	}

	public static function debugPage($isEnabled, $message) {
		if($isEnabled) {
			self::debug($message);
		}
	}

	public static function toJSON($id = null, $arr) {
		$newArr = array();
		$index = 0;
		foreach($arr as $obj) {
			$newArr[$index++] = $obj->toJSONObject();
		}
		return json_encode(array($id == null ? "list" : $id => $newArr));
	}

	public static function validateSession() {
		if( Scope::loadSessionVar("USER_SESSION") == null ) {
			header("Location: " . "login.php?erro=Pagina restrita a usuarios cadastrados.");
		}
	}

	public static function invalidateSession() {
		@session_start();
		@session_destroy();
		header("Location: " . "login.php?erro=Logout efetuado com sucesso!");
	}

	public static function redirect($url) {
		header("Location: " . $url);
	}

	public static function validateRequest() {
		$var = Scope::loadVar("erro");
		if( $var != null ) {
			echo $var;
		}
	}

	public static function callSetter($obj, $attribute, $value) {
		Util::debug("callSetter para $obj | $attribute | $value");
		$setterMethod = "set" . ucfirst($attribute);
		$obj->$setterMethod($value);
	}

	public static function callGetter($obj, $attribute) {
		$getterMethod = "get" . ucfirst($attribute);
		return $obj->$getterMethod();
	}
	
	public static function fillObject($class_name){
		$class = new ReflectionClass($class_name);
		$methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);
		$setters = array();

		foreach( $methods as $method ) {
			if( strstr($method->getName(), 'set')) {
				$setters[] = $method;
			}
		}
		
		$obj = new $class_name();
		
		for($ind=0;$ind<sizeof($setters); $ind++) {
			$att = self::lcfirst(substr($setters[$ind]->getName(),3));
			$attValue = Scope::loadVar($att);
			$setters[$ind]->invokeArgs($obj, array($attValue));
		}
		return $obj;
	}
	
	public static function lcfirst($str) {
		return (string)(strtolower(substr($str,0,1)).substr($str,1));
	}
}

//echo Util::debugPage(true, "teste este");
?>